<template>
  <span class="number-scroll-grow">
    <span ref="numberScroll" :data-time="time" class="number-scroll" :data-value="value"> 0 </span>
  </span>
</template>
   
  <script>
import { defineComponent } from 'vue'
export default defineComponent({
  name: 'numberScroll',
  props: {
    time: {
      type: Number,
      default: 5
    },
    value: {
      type: Number,
      default: 0
    },
    thousandSign: {
      type: Boolean,
      default: () => false
    }
  },
  data() {
    return {
      oldValue: 0
    }
  },
  methods: {
    numberScroll(ele) {
      let _this = this
      let value = _this.value - _this.oldValue
      let is_z = true
      if (value / Math.floor(value) != 1 && value > 0) {
        is_z = false
      }
      let step = (value * 10) / (_this.time * 200)
      let current = 0
      let start = _this.oldValue
      let t = setInterval(function () {
        start += step
        if (start > _this.value) {
          clearInterval(t)
          start = _this.value
          t = null
        }
        if (current === start) {
          return
        }
        
        if (is_z) {
          current = parseInt(start)
        } else {
          current = start.toFixed(1)
        }

        _this.oldValue = current
        if (_this.thousandSign) {
          ele.innerHTML = current.toString().replace(/(\d)(?=(?:\d{3}[+]?)+$)/g, '$1,')
        } else {
          ele.innerHTML = current.toString()
        }
      }, 10)
    }
  },
  mounted() {
    const observer = new IntersectionObserver(async (entries) => {
      if (entries[0].isIntersecting && entries[0].intersectionRatio > 0) {
        setTimeout(() => {
          this.numberScroll(this.$refs.numberScroll)
        }, 100)
      }
    })
    observer.observe(this.$refs.numberScroll)
  }
})
</script>
   
<style scoped>
.number-scroll-grow {
  transform: translateZ(0);
}
</style>